import fs from 'fs';
import { marked } from 'marked';
import { createRequire } from 'module';
import path, { dirname } from 'path';
import prettier from 'prettier';
import { fileURLToPath } from 'url';
import getCaseName from './utils/case-name/index.js';
import frontMatter from './utils/front-matter/index.js';
import { parse as YAMLparse } from './utils/yaml/index.js';

// 还没写完
marked.use({
  async: true,
  pedantic: false,
  gfm: true,
});

function copy(params) {
  exec('pbcopy').stdin.end(params);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const cwd = process.cwd();
const prettierrc = JSON.parse(
  fs.readFileSync(path.resolve(cwd, '.prettierrc'), 'utf8'),
);

let fp = path.resolve(cwd, 'components/pc/_basic');
let tp = path.resolve(cwd, 'src/pc/views');
let a = fs.readdirSync(fp, {
  // recursive: true
});
let test = true;

if (test) {
  a = [a[13]];
}

let r = '';
for (let i = 0; i < a.length; i++) {
  const e = a[i];
  if (e.includes('.DS_Store')) {
    continue;
  }
  let f = path.resolve(fp, e);
  if (fs.existsSync(f) && fs.statSync(f).isDirectory()) {
    let demoDir = path.resolve(f, '__demo__');
    if (fs.existsSync(demoDir)) {
      let a_ = fs.readdirSync(demoDir, {
        // recursive: true
      });

      if (test) {
        // a_ = [a_[0]];
      }
      for (let i_ = 0; i_ < a_.length; i_++) {
        const e_ = a_[i_];
        let demo = path.resolve(demoDir, e_);
        let r = fs.readFileSync(demo, 'utf8');
        let { attributes, body, bodyBegin, frontmatter } = frontMatter(r);
        const tokens = marked.lexer(body);
        r = paraseMD(tokens, {
          name: e,
          demoName: e_.replace(path.extname(e_), ''),
        });
      }
    }

    // r = await prettier.format(r, { ...prettierrc, parser: 'babel-ts' });
    // fs.writeFileSync(f, r, { encoding: 'utf-8' });
  }
}

async function paraseMD(params, other) {
  let { name, demoName } = other ?? {};
  const { ComponentsCaseName: demoComponentsCaseName } = getCaseName(demoName);

  let importString = '';
  let elementString = '';
  for (let i = 0; i < params.length; i++) {
    const e = params[i];
    let { type, raw, depth, lang, text, tokens } = e ?? {};
    // console.log(e);
    switch (type) {
      case 'code': {
        switch (lang) {
          case 'yaml': {
            let { title } = YAMLparse(text) || {};
            let a = Object.entries(title)
              .sort((a, b) => {
                return a[0] > b[0] ? 1 : -1;
              })
              .reverse()
              .map(v => v[1]);
            elementString += `<h2 class={['title']}>${a.join(' ')}</h2>`;
            break;
          }
          case 'vue': {
            let t = await prettier.format(text, {
              ...prettierrc,
              parser: 'vue',
            });
            let d = path.resolve(tp, name, 'demo');
            let p = path.resolve(d, `${demoComponentsCaseName}.vue`);
            if (!fs.existsSync(d)) {
              // fs.rmSync(d, { recursive: true, force: true });
              fs.mkdirSync(d);
            }
            fs.writeFileSync(p, t, {
              encoding: 'utf-8',
            });

            importString += `import ${demoComponentsCaseName} from './demo/'${demoComponentsCaseName}.vue;`;
            break;
          }

          default: {
            console.error('出现新语言：', lang);
            break;
          }
        }
        break;
      }
      case 'space': {
        break;
      }
      case 'heading': {
        break;
      }
      case 'paragraph': {
        break;
      }
      case 'hr': {
        break;
      }
      case 'text': {
        break;
      }
      case 'codespan': {
        break;
      }
      case 'strong': {
        break;
      }

      default: {
        console.error('出现新类型：', type);
        break;
      }
    }

    if (tokens?.length) {
      elementString += (await paraseMD(tokens, other).elementString) ?? '';
    }
  }

  elementString && console.log(elementString);
  return { importString, elementString };
}
